package com.liu.yubi.bimq;

import cn.hutool.json.JSONUtil;
import com.liu.yubi.common.ErrorCode;
import com.liu.yubi.exception.BusinessException;
import com.liu.yubi.manager.DBAiManager;
import com.liu.yubi.model.entity.Chart;
import com.liu.yubi.service.ChartService;
import com.liu.yubi.service.UserService;
import com.liu.yubi.utils.AiUtils;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

import static com.liu.yubi.model.enums.ChartStatusEnum.*;

/**
 * @author lqh
 * @since 2025-06-13 15:58
 * 消费者
 */
@Component
@Slf4j
public class BiMessageConsumer {

    @Resource
    private ChartService chartService;

    @Resource
    private DBAiManager aiManager;

    @Resource
    private UserService userService;


    @SneakyThrows
    @RabbitListener(queues = {"YuBi_common_queue"}, ackMode = "MANUAL") //指定消费者监听那个队列和消息确认机制
    public void receiveMessage(String message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {
        log.info ("receive message: {}", message);
        //判断消息是否为空
        if (StringUtils.isBlank (message)) {
            //拒绝消费
            channel.basicNack (deliveryTag, false, false);
            log.info ("消息拒绝接收!");
            log.info ("此消息正在被转发到死信队列中!");
            throw new BusinessException (ErrorCode.PARAMS_ERROR, "消息为空!");
        }
        //json字符串转为对象
        MQMessage mes = JSONUtil.toBean (message, MQMessage.class);
        Long chartId = mes.getChartId ();

        //判断图表数据是否存在
        Chart chart = chartService.getById (chartId);
        if (chart == null) {
            //拒绝消费
            channel.basicNack (deliveryTag, false, false);
            throw new BusinessException (ErrorCode.PARAMS_ERROR, "图表不存在!");
        }

        //先修改图表状态是running
        Chart Chart1 = new Chart ();
        Chart1.setStatus (RUNNING.getValue ());
        Chart1.setId (chart.getId ());
        boolean b = chartService.updateById (Chart1);
        if (!b) {
            //拒绝消费
            channel.basicNack (deliveryTag, false, false);
            chartService.handleErrorChart (chart.getId (), "更新图表执行状态失败!");
            return;

        }
        //调用AI
        String aiResponse;
        try {
            aiResponse = aiManager.doChat (AiUtils.AIInputMessage (chart.getGoal (), chart.getChartType (), chart.getChartData ()));
        }catch (Exception e){
            //拒绝消费
            channel.basicNack (deliveryTag, false, false);
            chartService.handleErrorChart (chart.getId (), "调用AI功能失败!");
            return;
        }
        //AI响应结果
        String genCode = AiUtils.extractJsCode (aiResponse);
        String genResult = AiUtils.extractAnalysis (aiResponse);
        //更新数据库
        //将生成代码转为json格式
        String genChart = AiUtils.genCodeToJson (genCode);
        Chart updateChart2 = new Chart ();
        updateChart2.setId (Chart1.getId ());
        updateChart2.setGenChart (genChart);
        updateChart2.setGenResult (genResult);
        //设置执行状态
        updateChart2.setStatus (SUCCEED.getValue ());
        boolean b1 = chartService.updateById (updateChart2);
        if (!b1) {
            //拒绝消费
            channel.basicNack (deliveryTag, false, false);
            chartService.handleErrorChart (updateChart2.getId (), "更新图表成功状态失败!");
            return;
        }
        //扣除用户积分
        userService.deductUserScore (chart.getUserId ());
        //消息手动确认消费
        channel.basicAck (deliveryTag, false);
    }

}

